using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Xml;
using Microsoft.Practices.RepositoryFactory.CodeGeneration.ObjectModel;
using Microsoft.Practices.RepositoryFactory.CodeGeneration.ObjectModel.Mappings;
using Microsoft.Practices.RepositoryFactory.CodeGeneration.ObjectModel.Mappings.Enums;
using Microsoft.Practices.RepositoryFactory.CodeGeneration.ObjectModel.Mappings.Helper;
using Microsoft.Practices.RepositoryFactory.CodeGeneration.ObjectModel.NamingConventions;
using Microsoft.Practices.RepositoryFactory.CommonHelpers;
using Microsoft.Practices.RepositoryFactory.CustomPages.Helpers;
using Microsoft.Practices.RepositoryFactory.SchemaDiscovery.ObjectModel.Base;
using Microsoft.Practices.WizardFramework;
using Resources = Microsoft.Practices.RepositoryFactory.Properties.Resources;

namespace Microsoft.Practices.RepositoryFactory.CustomPages
{
   /// <summary/>
   public partial class EntitySPMapperCP : CustomWizardPage
   {
      #region Fields

      private ArrayList entitiesStoredProcedureMappings;
      ConnectionStringSettings connectionSettings;
      string cnstring;
      EntitySerializerHelper serializer;
      private XmlDocument recipeState;
      private List<string> _missingStoredProcedures = new List<string>();
      #endregion

      #region Arguments

      /// <summary>
      /// Gets or sets the entities stored procedure mappings.
      /// </summary>
      /// <value>The entities stored procedure mappings.</value>
      [RecipeArgument]
      public ArrayList EntitiesStoredProcedureMappings
      {
         get
         {
            return this.entitiesStoredProcedureMappings;
         }
         set
         {
            this.entitiesStoredProcedureMappings = value;
         }
      }

      [RecipeArgument]
      public XmlDocument RecipeState
      {
         get
         {
            return this.recipeState;
         }
         set
         {
            this.recipeState = value;
         }
      }


      #endregion

      #region Constructors

      /// <summary>
      /// Initializes a new instance of the <see cref="T:EntitySPMapperCP"/> class.
      /// </summary>
      /// <param name="parent">The parent.</param>
      public EntitySPMapperCP(WizardForm parent)
         : base(parent)
      {
         InitializeComponent();
      }

      #endregion

      #region Event Handlers

      /// <summary>
      /// Called when [activated].
      /// </summary>
      public override void OnActivated()
      {
         IDictionaryService dictservice = (IDictionaryService)GetService(typeof(IDictionaryService));
         connectionSettings = (ConnectionStringSettings)dictservice.GetValue("ConnectionSettings");
         serializer = new EntitySerializerHelper(RecipeState);
         if (dictservice.GetValue("EntitiesStoredProcedureMappings") == null)
         {
            //First Time
            SetControlProperties(false);
            cnstring = connectionSettings.ConnectionString;
         }
         else
         {
            if (cnstring != connectionSettings.ConnectionString)
            {
               SetControlProperties(false);
               cnstring = connectionSettings.ConnectionString;
            }
            else
            {
               SetControlProperties(true);
            }

            dictservice.SetValue("EntitiesStoredProcedureMappings", null);
         }

         SaveArgument();
         base.OnActivated();
      }

      private void btnDelete_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities) ||
            !UIGuard.IsListBoxSelected(lstOperations))
         {
            return;
         }

         IUIService uiService = (IUIService)GetService(typeof(IUIService));
         if (uiService.ShowMessage(Resources.ConfirmDelete, null, MessageBoxButtons.YesNo) == DialogResult.Yes)
         {
            Entity entity = (Entity)lstEntities.SelectedItem;

            UIHelper.Finder = lstOperations.SelectedItem.ToString();
            EntityStoredProcedureMapping mapping = entity.StoredProcedureMappings.Find(UIHelper.FindByOperationName);

            entity.StoredProcedureMappings.Remove(mapping);

            lstOperations.Items.Remove(lstOperations.SelectedItem);

            if (lstOperations.Items.Count > 0)
            {
               lstOperations.SelectedIndex = 0;
               btnDelete.Enabled = true;
               btnEdit.Enabled = true;
            }
            else
            {
               btnDelete.Enabled = false;
               btnEdit.Enabled = false;
            }

            RefreshOperations(entity);
         }
      }

      private void btnEdit_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities) ||
            !UIGuard.IsListBoxSelected(lstOperations))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;
         UIHelper.Finder = lstOperations.SelectedItem.ToString();
         EntityStoredProcedureMapping mapping = entity.StoredProcedureMappings.Find(UIHelper.FindByOperationName);

         if (mapping != null)
         {
            Form form = new CreateMappingWizard(entity,
                                                connectionSettings,
                                                mapping.OperationType,
                                                mapping);

            if (form.ShowDialog(this) == DialogResult.OK)
            {
               RefreshOperations(entity);
            }
         }
      }

      private void btnAdd_Click(object sender, EventArgs e)
      {
         addContextMenu.Show(btnAdd, new Point(0, btnAdd.Height));
      }

      private void getOneToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         CreateMappingWizard form = new CreateMappingWizard(entity,
             connectionSettings,
             OperationType.GetOne);

         if (form.ShowDialog(this) == DialogResult.OK)
         {
            RefreshOperations(entity);
         }
      }

      private void getOneComplexToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         CreateMappingWizard form = new CreateMappingWizard(entity,
              connectionSettings, OperationType.GetOneComplex);

         if (form.ShowDialog(this) == DialogResult.OK)
         {
            RefreshOperations(entity);
         }
      }

      private void getManyToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         CreateMappingWizard form = new CreateMappingWizard(entity,
                                                            connectionSettings,
                                                            OperationType.GetMany);

         if (form.ShowDialog(this) == DialogResult.OK)
         {
            RefreshOperations(entity);
         }
      }

      private void getAllToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         CreateMappingWizard form = new CreateMappingWizard(entity,
                                                            connectionSettings,
                                                            OperationType.GetAll);

         if (form.ShowDialog(this) == DialogResult.OK)
         {
            RefreshOperations(entity);
         }
      }

      private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         if (IsSelectionValid(entity, OperationType.DeleteOne))
         {
            CreateMappingWizard form = new CreateMappingWizard(entity,
                                                           connectionSettings,
                                                           OperationType.DeleteOne);

            if (form.ShowDialog(this) == DialogResult.OK)
            {
               RefreshOperations(entity);
            }
         }
      }

      private void insertOneToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         if (IsSelectionValid(entity, OperationType.InsertOne))
         {
            CreateMappingWizard form = new CreateMappingWizard(entity,
                                                               connectionSettings,
                                                               OperationType.InsertOne);

            if (form.ShowDialog(this) == DialogResult.OK)
            {
               RefreshOperations(entity);
            };
         }
      }

      private void insertManyToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         if (IsSelectionValid(entity, OperationType.InsertMany))
         {
            CreateMappingWizard form = new CreateMappingWizard(entity,
                                                               connectionSettings,
                                                               OperationType.InsertMany);

            if (form.ShowDialog(this) == DialogResult.OK)
            {
               RefreshOperations(entity);
            };
         }
      }

      private void updateOneToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
         {
            return;
         }

         Entity entity = (Entity)lstEntities.SelectedItem;

         if (IsSelectionValid(entity, OperationType.UpdateOne))
         {
            CreateMappingWizard form = new CreateMappingWizard(entity,
                                                           connectionSettings,
                                                           OperationType.UpdateOne);

            if (form.ShowDialog(this) == DialogResult.OK)
            {
               RefreshOperations(entity);
            }
         }
      }

      private void lstEntities_SelectedIndexChanged(object sender, EventArgs e)
      {
         Entity entity = (Entity)lstEntities.SelectedItem;
         RefreshOperations(entity);
      }

      /// <summary>
      /// <see cref="P:Microsoft.WizardFramework.WizardPage.IsDataValid"/>
      /// Search for all the arguments that this Wizard gather
      /// If all of them are not null, then the Wizard can finish
      /// </summary>
      /// <value></value>
      public override bool IsDataValid
      {
         get
         {
            bool response = (lstEntities.Items.Count > 0);

            foreach (object item in lstEntities.Items)
            {
               Entity entity = (Entity)item;

               if (entity.StoredProcedureMappings == null ||
                   entity.StoredProcedureMappings.Count == 0)
               {
                  response = false;
                  break;
               }
            }

            return response;
         }
      }

      #endregion

      #region Private Implementation

      private void SetControlProperties(bool syncEntities)
      {
         IDictionaryService dictservice = (IDictionaryService)GetService(typeof(IDictionaryService));
         ArrayList entities = (ArrayList)dictservice.GetValue("Entities");
         ArrayList clonedEntities = clonedEntities = ClonerHelper.CloneEntities(entities);

         if (syncEntities)
         {
            ArrayList currentEntities = (ArrayList)dictservice.GetValue("EntitiesStoredProcedureMappings");

            foreach (Entity currentEntity in currentEntities)
            {
               Entity entity = UIHelper.FindEntity(clonedEntities, currentEntity.Name);

               if (entity != null)
               {
                  clonedEntities.Remove(entity);
                  clonedEntities.Add(currentEntity);
               }
            }
         }

         Cursor.Current = Cursors.WaitCursor;

         try
         {
            ProvideDefaultMappings(clonedEntities, UIHelper.GetStoredProcedures(connectionSettings));
         }
         catch (Exception ex)
         {
            Debug.WriteLine(ex.Message);
            IUIService uiService = (IUIService)GetService(typeof(IUIService));
            uiService.ShowMessage(Microsoft.Practices.RepositoryFactory.Properties.Resources.ErrorObtainingSPList);
         }

         Cursor.Current = Cursors.Default;
         UIHelper.FillEntitiesListBox(lstEntities, clonedEntities);
         SetControls();
         EnableControls(lstEntities.Items.Count > 0);

         if (lstEntities.Items.Count > 0)
         {
            lstEntities.SelectedIndex = 0;
            RefreshOperations((Entity)lstEntities.SelectedItem);
         }
      }

      private void SetControls()
      {
         lstEntities.DisplayMember = Resources.EntityNameDisplayMember;
      }

      private void RefreshOperations(Entity entity)
      {
         lstOperations.Items.Clear();

         foreach (EntityStoredProcedureMapping mapping in entity.StoredProcedureMappings)
         {
            lstOperations.Items.Add(mapping.OperationName);
         }

         if (lstOperations.Items.Count > 0)
         {
            lstOperations.SelectedIndex = 0;
            btnDelete.Enabled = true;
            btnEdit.Enabled = true;
         }
         else
         {
            btnDelete.Enabled = false;
            btnEdit.Enabled = false;
         }

         SaveArgument();
      }

      private void EnableControls(bool enable)
      {
         btnAdd.Enabled = enable;
         btnDelete.Enabled = enable;
         btnEdit.Enabled = enable;
      }

      private bool IsSelectionValid(Entity entity, OperationType operationType)
      {
         foreach (EntityStoredProcedureMapping mapping in entity.StoredProcedureMappings)
         {
            if (mapping.OperationType == operationType)
            {
               IUIService uiService = (IUIService)GetService(typeof(IUIService));
               uiService.ShowMessage(Resources.MappingExists);
               return false;
            }
         }

         return true;
      }

      private void ProvideDefaultMappings(ArrayList entities, List<StoredProcedure> storedProcedures)
      {
         // Clear the list of missing stored procedures.
         _missingStoredProcedures.Clear();

         foreach (object item in entities)
         {
            Entity entity = ((Entity)item);

            if (!HasPreviousInformation(entity))
            {
               if (entity.StoredProcedureMappings.Count == 0)
               {
                  ProvideMapping(entity, storedProcedures, OperationType.GetAll);
                  ProvideMapping(entity, storedProcedures, OperationType.GetOne);
                  ProvideMapping(entity, storedProcedures, OperationType.GetOneComplex);
                  ProvideMapping(entity, storedProcedures, OperationType.GetMany); 
                  ProvideMapping(entity, storedProcedures, OperationType.InsertOne);
                  ProvideMapping(entity, storedProcedures, OperationType.InsertMany);
                  ProvideMapping(entity, storedProcedures, OperationType.UpdateOne);
                  ProvideMapping(entity, storedProcedures, OperationType.UpdateMany);
                  ProvideMapping(entity, storedProcedures, OperationType.DeleteOne);
                  ProvideMapping(entity, storedProcedures, OperationType.DeleteMany);
               }
            }
            else
            {
               LoadSavedMapping(entity, storedProcedures);
            }
         }

         // If we have any stored procedure that could not be found, then warns the user.
         if (_missingStoredProcedures.Count > 0)
         {
            IUIService uiService = (IUIService)GetService(typeof(IUIService));
            StringBuilder sb = new StringBuilder();
            foreach (string spName in _missingStoredProcedures)
            {
               if (sb.Length != 0)
                  sb.Append(", ");
               sb.Append(spName);
            }

            _missingStoredProcedures.Clear();
            uiService.ShowMessage(string.Format(Resources.MissingStoredProcedures, sb));
         }
      }

      private bool HasPreviousInformation(Entity entity)
      {
         return serializer.HasStateInformation(entity);
      }

      private void LoadSavedMapping(Entity entity, List<StoredProcedure> storedProcedures)
      {
         XmlNode node = serializer.GetEntityStoredData(entity);

         //Read persisted operations
         foreach (XmlNode operationNode in node.ChildNodes)
         {
            string procedureName = operationNode.Attributes["procedure"].Value;
            bool hasInputParameters = bool.Parse(operationNode.Attributes["hasInputParameters"].Value);
            string operatioName = operationNode.Attributes["operationName"].Value;
            OperationType operationType = FindOperationTypeByName(operationNode.Attributes["operationType"].Value);
            StoredProcedure sp = storedProcedures.Find(delegate(StoredProcedure current) { return current.Name == procedureName; });

            if (sp != null)
            {
               EntityStoredProcedureMapping currentMapping = GetExistingMapping(entity.StoredProcedureMappings, operatioName, operationType);
               if (currentMapping == null)
               {
                  currentMapping = new EntityStoredProcedureMapping(procedureName, hasInputParameters, operatioName, operationType);
                  entity.StoredProcedureMappings.Add(currentMapping);
               }
               currentMapping.ParameterMappings.Clear();

               XmlNodeList parameterNodes = operationNode.SelectNodes("parameter");



               foreach (XmlNode parameterNode in parameterNodes)
               {
                  string propertyName = parameterNode.Attributes["propertyName"].Value;
                  string spParameterName = parameterNode.Attributes["parameterName"].Value;
                  int parameterDirection = int.Parse(parameterNode.Attributes["parameterDirection"].Value);

                  List<Parameter> parameters = UIHelper.GetParameters(connectionSettings, sp, ParameterDirection.ReturnValue);
                  parameters.AddRange(sp.Parameters);

                  Parameter parameter = FindStoredProcedureParameter(parameters, (ParameterDirection)parameterDirection, spParameterName);
                  if (parameter != null)
                  {
                     if (EntityContainsProperty(propertyName, entity))
                     {
                        currentMapping.ParameterMappings.Add(new PropertyParameterMapping(propertyName, UIHelper.CloneParameter(parameter)));
                     }
                  }
               }

               XmlNode identityNode = operationNode.SelectSingleNode("identity");

               if (identityNode != null)
               {
                  Identity identity = new Identity();
                  identity.Name = identityNode.Attributes["name"].Value;

                  foreach (XmlNode identityParamNode in identityNode.ChildNodes)
                  {
                     string propertyName = identityParamNode.Attributes["propertyName"].Value;
                     string spParameterName = identityParamNode.Attributes["parameterName"].Value;
                     int parameterDirection = int.Parse(identityParamNode.Attributes["parameterDirection"].Value);

                     List<Parameter> parameters = UIHelper.GetParameters(connectionSettings, sp, ParameterDirection.ReturnValue);
                     parameters.AddRange(sp.Parameters);

                     Parameter parameter = FindStoredProcedureParameter(parameters, (ParameterDirection)parameterDirection, spParameterName);

                     if (parameter != null)
                     {
                        identity.ParameterMappings.Add(new PropertyParameterMapping(propertyName, UIHelper.CloneParameter(parameter)));
                     }
                  }
                  currentMapping.Identity = identity;
               }
            }
         }
      }

      private bool EntityContainsProperty(string propertyName, Entity entity)
      {
         foreach (Property property in entity.Properties)
         {
            if (string.Compare(property.Name, propertyName, StringComparison.InvariantCultureIgnoreCase) == 0)
            {
               return true;
            }
         }

         return false;
      }

      private EntityStoredProcedureMapping GetExistingMapping(List<EntityStoredProcedureMapping> entityMappings, string operatioName, OperationType operationType)
      {
         foreach (EntityStoredProcedureMapping mapping in entityMappings)
         {
            if (string.Compare(mapping.OperationName, operatioName, true) == 0 && mapping.OperationType == operationType)
            {
               return mapping;
            }
         }

         return null;
      }

      private Parameter FindStoredProcedureParameter(List<Parameter> parameters, ParameterDirection parameterDirection, string parameterName)
      {
         foreach (Parameter parameter in parameters)
         {
            if (string.Compare(parameter.Name, parameterName, true) == 0 && parameter.Direction == parameterDirection)
            {
               return parameter;
            }
         }
         return null;
      }

      private OperationType FindOperationTypeByName(string operationType)
      {
         switch (operationType)
         {
            case "DeleteOne":
               return OperationType.DeleteOne;
            case "DeleteMany":
               return OperationType.DeleteMany;
            case "GetAll":
               return OperationType.GetAll;
            case "GetMany":
               return OperationType.GetMany;
            case "GetOne":
               return OperationType.GetOne;
            case "GetOneComplex":
               return OperationType.GetOneComplex;
            case "InsertOne":
               return OperationType.InsertOne;
            case "InsertMany":
               return OperationType.InsertMany;
            case "UpdateOne":
               return OperationType.UpdateOne;
            case "UpdateMany":
               return OperationType.UpdateMany;
         }
         return OperationType.DeleteOne;
      }

      private void ProvideMapping(Entity entity, List<StoredProcedure> storedProcedures, OperationType opType)
      {
         const string IDENTITY = "Identity";

         switch (opType)
         {
            case OperationType.DeleteOne:
               UIHelper.Finder = NamingHelper.GetSPName(entity.Name, StoredProcedureType.Delete);
               break;
            case OperationType.DeleteMany:
               UIHelper.Finder = NamingHelper.GetSPName(entity.Name, StoredProcedureType.Delete);
               break;
            case OperationType.InsertOne:
               UIHelper.Finder = NamingHelper.GetSPName(entity.Name, StoredProcedureType.Insert);
               break;
            case OperationType.InsertMany:
               UIHelper.Finder = NamingHelper.GetSPName(entity.Name, StoredProcedureType.Insert);
               break;
            case OperationType.UpdateOne:
               UIHelper.Finder = NamingHelper.GetSPName(entity.Name, StoredProcedureType.Update);
               break;
            case OperationType.UpdateMany:
               UIHelper.Finder = NamingHelper.GetSPName(entity.Name, StoredProcedureType.Update);
               break;
            case OperationType.GetOne:
               //We cannot provide default mapping for this operation because at this point we dont have the Table object
               break;
            case OperationType.GetOneComplex:
               //We cannot provide default mapping for this operation because at this point we dont have the Table object
               break;
            case OperationType.GetMany:
               //We cannot provide default mapping for this operation because we cannot guess the Many criteria
               break;
            case OperationType.GetAll:
               UIHelper.Finder = NamingHelper.GetSPName(entity.Name, StoredProcedureType.GetAll);
               break;
            default:
               break;
         }

         StoredProcedure sp = storedProcedures.Find(UIHelper.FindByStoredProcedureName);

         if (sp == null)
         {
            _missingStoredProcedures.Add(UIHelper.Finder);
         }
         else
         {
            // Check for both IN and IN/OUT params.  If either is true, then 
            // the stored proc has input params.
            bool hasInOrInOutParams =
                (UIHelper.GetParameters(this.connectionSettings, sp, ParameterDirection.Input).Count > 0) ||
                (UIHelper.GetParameters(this.connectionSettings, sp, ParameterDirection.InputOutput).Count > 0);

            EntityStoredProcedureMapping mapping =
                new EntityStoredProcedureMapping(
                sp.Name,
                hasInOrInOutParams,
                sp.Name,
                opType);

            List<Parameter> parameters = new List<Parameter>();

            if (opType == OperationType.GetAll)
            {
               try
               {
                  parameters = UIHelper.GetParameters(connectionSettings, sp, ParameterDirection.ReturnValue);
               }
               catch
               {
                  IUIService uiService = (IUIService)GetService(typeof(IUIService));
                  uiService.ShowMessage(Microsoft.Practices.RepositoryFactory.Properties.Resources.ErrorObtainingSPResultSet);
               }
            }

            if (opType != OperationType.DeleteOne)
            {
               foreach (Property property in entity.Properties)
               {
                  Parameter parameter = null;

                  if (opType == OperationType.GetAll)
                  {
                     parameter = UIHelper.FindStoredProcedureParameter(parameters, ParameterDirection.ReturnValue, property.Name);
                  }
                  else
                  {
                     parameter = UIHelper.FindStoredProcedureParameter(sp, property.Name);
                  }

                  if (parameter != null)
                  {
                     PropertyParameterMapping parameterMapping =
                         new PropertyParameterMapping(
                            property.Name,
                            UIHelper.CloneParameter(parameter));

                     mapping.ParameterMappings.Add(parameterMapping);
                  }
               }
            }

            if (opType == OperationType.DeleteOne ||
                opType == OperationType.GetAll)
            {

               Identity identity = new Identity();
               identity.Name = NamingHelper.GetOperationName(sp.Name) + IDENTITY;

               foreach (Parameter parameter in sp.Parameters)
               {
                  if (parameter.Direction == ParameterDirection.Input)
                  {
                     PropertyParameterMapping mapping1 =
                         new PropertyParameterMapping(parameter.Name,
                         UIHelper.CloneParameter(parameter));

                     identity.ParameterMappings.Add(mapping1);
                  }
               }
               mapping.Identity = identity;
            }

            if (mapping.ParameterMappings.Count > 0 ||
                (mapping.Identity != null && mapping.Identity.ParameterMappings.Count > 0))
            {
               entity.StoredProcedureMappings.Add(mapping);
            }
         }
      }

      private ArrayList GetEntitySPMappings()
      {
         ArrayList mappings = new ArrayList();

         foreach (object item in lstEntities.Items)
         {
            mappings.Add((Entity)item);
         }

         return mappings;
      }

      private void SaveArgument()
      {
         ArrayList mapping = GetEntitySPMappings();
         IDictionaryService dictservice = (IDictionaryService)GetService(typeof(IDictionaryService));
         dictservice.SetValue("EntitiesStoredProcedureMappings", mapping);
      }
      #endregion

      private void EntitySPMapperCP_Enter(object sender, EventArgs e)
      {
         // Remove menu items specific to ODP if the provider is not ODP
         if (String.Equals(connectionSettings.ProviderName, DatabaseProvider.ODP)
            || this.addContextMenu == null)
            return;
         
         try
         {
            this.addContextMenu.Items.RemoveByKey("insertManyToolStripMenuItem");
            this.addContextMenu.Items.RemoveByKey("updateManyToolStripMenuItem");
            this.addContextMenu.Items.RemoveByKey("deleteManyToolStripMenuItem");
         }
         catch
         { 
            // no matter what, don't fail
         }
      }

      private void updateManyToolStripMenuItem_Click(object sender, EventArgs e)
      {
         if (!UIGuard.IsListBoxSelected(lstEntities))
            return;

         Entity entity = (Entity)lstEntities.SelectedItem;

         if (IsSelectionValid(entity, OperationType.UpdateMany))
         {
            CreateMappingWizard form = new CreateMappingWizard(entity,
                                                           connectionSettings,
                                                           OperationType.UpdateMany);

            if (form.ShowDialog(this) == DialogResult.OK)
            {
               RefreshOperations(entity);
            }
         }
      }

   }
}